﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using Barbar.MapReport.Common;

namespace Barbar.MapReport.DataSource {
  [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
  public class Polyline : ReadOnlyCollection<Point>, IGeoBound {
    private GeoBound m_GeoBound;

    private void EnsureGeoBound() {
      if (m_GeoBound == null) {
        m_GeoBound = GeoBound.ComputeSharedGeoBound<Point>(this);
      }
    }

    public Polyline(IList<Point> list)
      : base(list) {
    }

    #region IGeoBound Members

    public IGeoPoint Northeast {
      get {
        EnsureGeoBound();
        return m_GeoBound.Northeast;
      }
    }

    public IGeoPoint Southwest {
      get {
        EnsureGeoBound();
        return m_GeoBound.Southwest;
      }
    }

    #endregion

    public bool ContainsPoint(IGeoPoint point) {
      GeoBound geoBound = new GeoBound(this);
      if (!geoBound.ContainsPoint(point))
        return false;

      int i, j;
      bool result = false;
      for (i = 0, j = this.Count - 1; i < this.Count; j = i++)
        if ((((this[i].Latitude <= point.Latitude) && (point.Latitude < this[j].Latitude)) ||
          ((this[j].Latitude <= point.Latitude) && (point.Latitude < this[i].Latitude))) &&
          (point.Longitude < (this[j].Longitude - this[i].Longitude) * (point.Latitude - this[i].Latitude) / (this[j].Latitude - this[i].Latitude) + this[i].Longitude))
          result = !result;
      return result;
    }
  }
}
